package com.ant.androidBuddy;

import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.ViewConfiguration;
import android.widget.TextView;
import android.widget.Toast;

public class SaveFileActivity extends Activity{

	@Override
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.save_file);
		//show the up button on the action bar
		ActionBar actionBar=getActionBar();
		actionBar.setDisplayHomeAsUpEnabled(true);
		//force overflow on devices with physical menu key
	    try {
	        ViewConfiguration config = ViewConfiguration.get(this);
	        Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
	        if(menuKeyField != null) {
	            menuKeyField.setAccessible(true);
	            menuKeyField.setBoolean(config, false);
	        }
	    } catch (Exception ex) {
	        // Ignore
	    }
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		//add the action buttons
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.save_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
	{    
		switch (item.getItemId()) 
		{        
		case android.R.id.home:{
			//go home
			Intent intent = new Intent(this, AnimationActivity.class);            
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);            
			return true;
		}
		case R.id.btn_save:{
			//save
			save();
			return true;
		}
		case R.id.btn_cancel:{
			//cancel
			finish();
		}
		default:   {
			//this shouldn't happen
			return super.onOptionsItemSelected(item);    
		}
		}
	}

	//save the file
	public void save(){
		Intent in = getIntent();
		//get the code to save
		String commands=in.getStringExtra("cmd");
		TextView tv = (TextView)findViewById(R.id.file_name);
		String name = tv.getText().toString();
		//if the name is blank
		if(name.equals("")){
			Toast.makeText(getApplicationContext(), R.string.invalidName, Toast.LENGTH_LONG).show();
		}
		//if it was valid
		else{
			try{
				//try to save it
				FileOutputStream fos = openFileOutput(name, Context.MODE_PRIVATE);
				byte[] bytes=commands.getBytes();
				fos.write(bytes);
				fos.close();
				Toast.makeText(getApplicationContext(), name +" was saved", Toast.LENGTH_LONG).show();
				finish();
			}
			catch(IOException e){
				Toast.makeText(getApplicationContext(), "IOException while saving", Toast.LENGTH_LONG).show();
			}

		}
	}
}
